#include "svmpredict.h"

/*
  Extended version with dense format
*/
double svmpredict::predict(FILE *input, FILE *output)
{
	int correct = 0;
	int total = 0;
	double error = 0;
	double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;

	int svm_type=svm_get_svm_type(model);
	int nr_class=svm_get_nr_class(model);
	int *labels=(int *) malloc(nr_class*sizeof(int));
	double *prob_estimates=NULL;
	int j;

	int type, dim;

	if(predict_probability)
	{
		if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
			printf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
		else
		{
			svm_get_labels(model,labels);
			prob_estimates = (double *) malloc(nr_class*sizeof(double));
			fprintf(output,"labels");		
			for(j=0;j<nr_class;j++)
				fprintf(output," %d",labels[j]);
			fprintf(output,"\n");
		}
	}

	type = 0; // sparse format
	dim = 0;
	j = 0;

	for(int c = fgetc(input); (c != EOF) && (dim == 0); c = fgetc(input))
	{
		switch(c)
		{
			case '\n':
				dim = j;
				break;

			case ':':
				++j;
				break;

			case ',':
				++j;
				type = 1;
				break;

			default:
				;
		}
	}
	rewind(input);
	double mape=0;
	while(1)
	{
		int i = 0;
		int c;
		double target,v;

		if (type == 0) // sparse format
		{
			if (fscanf(input,"%lf",&target) == EOF)
				break;
		}
		else if (type == 1) // dense format
		{
			c = getc(input);

			if (c == EOF)
			{
				break;
			}
			else
			{
				ungetc(c,input);
			}
		}

		while(1)
		{
			if(i>=max_nr_attr-1)	// need one more for index = -1
			{
				max_nr_attr *= 2;
				x = (struct svm_node *) realloc(x,max_nr_attr*sizeof(struct svm_node));
			}

			do {
				c = getc(input);
				if((c=='\n') || (c==EOF)) break;
			} while(isspace(c));
			if((c=='\n') || (c==EOF)) break;

			ungetc(c,input);

			if (type == 0) // sparse format
			{
#ifdef INT_FEAT
				int tmpindex;
				int tmpvalue;
				fscanf(input,"%d:%d",&tmpindex,&tmpvalue);
                x[i].index = tmpindex;
				x[i].value = tmpvalue;
#else
				fscanf(input,"%d:%lf",&x[i].index,&x[i].value);
#endif
				++i;
			}
			else if ((type == 1) && (i < dim)) // dense format, read a feature
			{
				x[i].index = i;
#ifdef INT_FEAT
				int tmpvalue;
                fscanf(input, "%d,", &tmpvalue);
				x[i].value = tmpvalue;
#else
				fscanf(input, "%lf,", &(x[i].value));
#endif
				++i;
			}
			else if ((type == 1) && (i >= dim)) // dense format, read the label
			{
				fscanf(input,"%lf",&target);
			}
		}	


		x[i++].index = -1;

		if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
		{
			v = svm_predict_probability(model,x,prob_estimates);
			fprintf(output,"%g ",v);
			for(j=0;j<nr_class;j++)
				fprintf(output,"%g ",prob_estimates[j]);
			fprintf(output,"\n");
		}
		else
		{
			v = svm_predict(model,x);
			fprintf(output,"%g\n",v);
		}

		if(v == target)
			++correct;
		error += (v-target)*(v-target);
		sumv += v;
		sumy += target;
		sumvv += v*v;
		sumyy += target*target;
		sumvy += v*target;

		if (v>=target)
		{
			mape += (v-target)/target;
		}
		else
		{
			mape += (target-v)/target;
		}
		++total;
	}
	//printf("Accuracy = %g%% (%d/%d) (classification)\n",
		//(double)correct/total*100,correct,total);
	//printf("Mean squared error = %g (regression)\n",error/total);
	/*printf("Squared correlation coefficient = %g (regression)\n",
		((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
		((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))
		);*/

	double predictResult = mape/total;
		//((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
		//((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy));

	if(predict_probability)
	{
		free(prob_estimates);
		free(labels);
	}

	return predictResult;
}

double svmpredict::DoPredict(char* inputFileName, char* outputFileName, char* modelFileName)
{
	max_line_len = 100000;
	max_nr_attr = 64;
	predict_probability=0;
	predict_rankresult=0;

	FILE *input, *output;
	input = fopen(inputFileName,"r");
	output = fopen(outputFileName,"w");

	if((model=svm_load_model(modelFileName))==0)
	{
		fprintf(stderr,"can't open model file %s\n",modelFileName);
		exit(1);
	}

	//printf("Kernel type: %d\n", model->param.kernel_type);
	
	line = (char *) malloc(max_line_len*sizeof(char));
	x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));

	double predictResult = predict(input, output);

    fclose(input);

	svm_destroy_model(model);
	free(line);
	free(x);	
	fclose(output);

	return predictResult;
}